package test21.udp;

import java.io.IOException;
import java.net.*;

public class UDPSenderB {
    public static void main(String[] args) throws IOException {
        //1.创建 DatagramSocket 对象，准备在9998端口 接收数据
        DatagramSocket datagramSocket = new DatagramSocket(9998);
        //2. 将需要发送的数据，封装到 DatagramPacket对象
        byte[] data = "hello 明天吃火锅~".getBytes();
        //封装的 DatagramPacket对象 data 内容字节数组 , data.length , 主机(IP) , 端口
        DatagramPacket datagramPacket =
                new DatagramPacket(data, data.length,
                        InetAddress.getByName("10.254.41.224"), 9999);
        //发送数据包
        datagramSocket.send(datagramPacket);

        //== 接收从A端回复的信息
        byte[] buf = new byte[1024];
        DatagramPacket datagramPacket1 = new DatagramPacket(buf, buf.length);
        datagramSocket.receive(datagramPacket1);
        //拆包
        int length = datagramPacket1.getLength();
        byte[] data1 = datagramPacket1.getData();
        String s = new String(data1, 0, length);
        System.out.println(s);
        //关闭资源
        datagramSocket.close();
        System.out.println("B端退出");
    }
}
